import React, { useContext } from 'react';
import { Form, Input, message, Modal, Select } from 'antd';
import { useRequest } from 'ahooks';
import { Category } from './index';
import { apiPostArticleCategory } from '@/api/article.api';

export default (props: {
  context: React.Context<any>;
  updateListRow: (newData: Category) => void;
}) => {
  const { state, setState } = useContext(props.context);

  const [form] = Form.useForm();
  const { run: submit, loading } = useRequest(
    values => {
      return apiPostArticleCategory({ ...state.data, ...values });
    },
    {
      manual: true,
      onSuccess: data => {
        if (data.status) {
          props.updateListRow({ ...state.data, ...data.data });
          message.success('保存成功');
        }
      },
    },
  );

  return (
    <Modal
      visible={state.visible}
      title={state?.data?.id ? '编辑分类' : '添加分类'}
      confirmLoading={loading}
      onOk={() => {
        form.submit();
      }}
      onCancel={() => {
        setState({
          ...state,
          visible: false,
          data: undefined,
        });
      }}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        onFinish={submit}
        scrollToFirstError={true}
        initialValues={state?.data}
      >
        <Form.Item
          name={'name'}
          label={'分类名称'}
          rules={[{ required: true }]}
        >
          <Input autoFocus={true} autoComplete={'off'} />
        </Form.Item>

        <Form.Item name={'sort'} label={'顺序'} extra={'从小到大排序'}>
          <Input type={'number'} />
        </Form.Item>
      </Form>
    </Modal>
  );
};
